<template>
    <div>
        <flexbox justify="flex-end" v-if="detail.dataSource === '外部' && !disabled">
            <div style="flex: 1">
                <slot></slot>
            </div>
            <a-button class="margin-l-8" type="primary" :disabled="disabled" @click="handleAdd">添加</a-button>
        </flexbox>
        <custom-table
            ref="ruleTableRef"
            :rules="tableRules"
            class="margin-t-16 prcess-version-table"
            size="small"
            :locale="locale"
            rowKey="id"
            :pagination="false"
            :columns="columns"
            :data-source="newList"
            v-if="detail.dataSource === '外部'"
        >
            <template #versionNumber="{ record }">
                <span v-if="disabled">{{ record.versionNumber }}</span>
                <a-input :maxlength="200" allow-clear v-model:value="record.versionNumber" v-else />
            </template>
            <template #requireTitle="{ record }">
                <a-tooltip v-if="disabled" :title="record.requireTitle">
                    <span>{{ record.requireTitle }}</span>
                </a-tooltip>
                <a-input :maxlength="200" allow-clear v-model:value="record.requireTitle" v-else />
            </template>
            <template #planRequires="{ record }">
                <flexbox v-if="disabled">
                    <span v-if="record.planRequires || record.planRequires == 0">{{ record.planRequires }}</span>
                    <a-tag color="red" v-else>未填报</a-tag>
                </flexbox>
                <a-input-number :min="0" v-model:value="record.planRequires" v-else />
            </template>
            <template #planOnlineTime="{ record, index }">
                <flexbox>
                    <flexbox v-if="disabled">
                        <span v-if="record.planOnlineTime">{{ $filters.dateFilter(record.planOnlineTime) }}</span>
                        <a-tag color="red" v-else>未填报</a-tag>
                    </flexbox>
                    <h-date-picker-cell v-model:value="record.planOnlineTime" :disabledDate="false" v-else />
                    <div class="margin-l-8" v-if="!disabled && index === newList.length - 1">
                        <PlusCircleOutlined @click="handleAdd" />
                        <MinusCircleOutlined class="margin-l-8" @click="handleRemove(index)" />
                    </div>
                </flexbox>
            </template>
        </custom-table>

        <custom-table
            ref="ruleTableRef"
            :rules="tableRules"
            class="margin-t-16 prcess-version-table"
            size="small"
            rowKey="id"
            :pagination="false"
            :columns="columns"
            :data-source="newList"
            v-else
        >
            <template #requireTitle="{ record }">
                <a-tooltip v-if="disabled" :title="record.requireTitle">
                    <span>{{ record.requireTitle }}</span>
                </a-tooltip>
                <a-input :maxlength="100" allow-clear v-model:value="record.requireTitle" v-else />
            </template>
            <template #energyManage="{ record }">
                <router-link :to="{ path: '/energyManage/versionReportHistory/detail', query: { id: record.requireId } }">详情</router-link>
            </template>
            <template #versionNumber="{ record }">
                <router-link :to="{ path: '/version/versionDetail', query: { id: record.requireId } }">{{ record.versionNumber }}</router-link>
            </template>
            <template #planRequires="{ record }">
                <a @click="jumpToProList(1, record.planRequireIds)" v-if="record.planRequires">{{ record.planRequires }}</a>
                <span v-else>{{ record.planRequires }}</span>
            </template>
            <template #planOnlineTime="{ record }">
                <span>{{ $filters.dateFilter(record.planOnlineTime) }}</span>
            </template>
        </custom-table>
    </div>
</template>

<script lang="tsx">
import api from '@/api';
import { message } from 'ant-design-vue/es';
import { useRouter } from 'vue-router';
import { PlusCircleOutlined, MinusCircleOutlined } from '@ant-design/icons-vue';
import { detailColumns } from '@/views/energyManage/analysisReport/config/detailColumns';
import { CustomTable, HDatePickerCell } from '@/components';
import { defineComponent, ref, unref, reactive, toRefs, computed, watch } from 'vue';
export default defineComponent({
    components: {
        CustomTable,
        HDatePickerCell,
        PlusCircleOutlined,
        MinusCircleOutlined
    },
    props: {
        list: {
            type: Array,
            default: () => []
        },
        releaseVersionList:{
            type: Array,
            default: () => []
        },
        unOnlineVersionList:{
            type: Array,
            default: () => []
        },
        detail: {
            type: Object,
            default: () => ({})
        },
        hasAuth: {
            type: Boolean,
            default: false
        },
        isNoData: {
            type: Boolean,
            default: false
        }
    },
    setup(props) {
        const router = useRouter();
        const { columnsC } = detailColumns;
        const ruleTableRef = ref<any>();
        const state = reactive<any>({
            newList: [],
            locale: { emptyText: () => <a-empty description="未填报"/>}
        });
        const validateVersionNumber = async (rule: any, value: any) => {
            if (value) {
                const reg1 = /^[a-zA-Z0-9-]+\.[a-zA-Z0-9]+\.[a-zA-Z0-9]+$/gi;
                const reg2 = /^[a-zA-Z0-9-]+\.[a-zA-Z0-9]+\.[a-zA-Z0-9]+\.[a-zA-Z0-9]+$/gi;
                return (reg1.test(value) || reg2.test(value) ) ? Promise.resolve() : Promise.reject('格式不正确');
            } else {
                return Promise.resolve();
            }
        };
        // 表格规则
        const tableRules = computed(() => {
            if (props.detail.dataSource === '外部') {
                return {
                    versionNumber:[
                        {required:true, message:'版本号不能为空'},
                        {validator:validateVersionNumber, message: '版本号不正确，请按照X.X.X的命名格式命名版本号，其中每一位允许数字英文或“-”符号' }
                    ],
                    requireTitle: [{ required: true, message: '版本概述不能为空' }]
                };
            } else {
                return {
                    requireTitle: [{ required: true, message: '版本概述不能为空' }]
                };
            }
        });
        const disabled = computed(() => {
            return +props.detail.stage > 2 || !props.hasAuth || props.isNoData;
        });
        const columns = computed(() => {
            return columnsC;
            // return props.detail.dataSource === '外部' ? columnsC : [...columnsC,{
            //     title:'版本能效',
            //     dataIndex:'energyManage',
            //     width:100,
            //     slots: { customRender: 'energyManage' },
            // }];
        });
        const validate = async () => {
            let res = unref(disabled);
            if (!res) {
                if (props.detail.dataSource === '外部' && !state.newList.length && !props.releaseVersionList.length && !props.unOnlineVersionList.length) {
                    message.error('请至少添加一个版本');
                    res = false;
                }
                else {
                    res = await unref(ruleTableRef).validate();
                }
                if (!res) {
                    const doms = document.getElementsByClassName('prcess-version-table');
                    const dom = doms[0];
                    dom?.scrollIntoView({ block: 'center', inline: 'center' });
                }
            }
            return res;
        };
        const handleAdd = () => {
            state.newList.push({
                versionNumber:'',
                status: '进行中',
                requireTitle: '',
                planRequires: null,
                type: '3',
                planOnlineTime: '',
                systemReportId: props.detail.id
            });
        };
        const handleRemove = async (index) => {
            const id = state.newList[index].id;
            if (id) {
                const query = {
                    id
                };
                const { success } = await api.requireReportModel.deleteRRInfoById(query);
                if (success) {
                    state.newList.splice(index, 1);
                }
            } else {
                state.newList.splice(index, 1);
            }
        };
        const jumpToProList = (type, ids) => {
            router.push({
                path: '/energyManage/analysisReport/proList',
                query: {
                    ids,
                    type,
                    systemName: props.detail.systemName
                }
            });
        };
        watch(
            () => props.list,
            (n) => {
                state.newList = [...n];
            },
            {
                immediate: true
            }
        );

        return {
            columns,
            ruleTableRef,
            tableRules,
            disabled,
            ...toRefs(state),
            handleAdd,
            handleRemove,
            jumpToProList,
            validate
        };
    }
});
</script>

<style scoped>
</style>